package cn.com.cym.gamezao.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 数学相关的工具方法(包含算法)
 */
public class MathUtils {

    private static final String PRE="auth";
    /**
     * 根据用户名生成一个识别id
     * @param userName userName
     * @return re
     */
    public static String mathUserName(String userName){
        final int length = userName.length();
        String substring = userName.substring(length / 2);
        substring+=PRE;
        return  substring;
    }

    /**
     *
     * @param userName 用户名
     * @return flag
     */
    public static boolean rexCheckUserName(String userName) {
        // 昵称格式：限16个字符，支持中英文、数字、减号或下划线
        String regStr = "^[\\u4e00-\\u9fa5_a-zA-Z0-9-]{1,16}$";
        return userName.matches(regStr);
    }

    /**
     * 正则表达式验证密码
     * @param password 密码
     * @return flag
     */
    public static boolean rexCheckPassword(String password) {
        // 8-20 位，字母、数字、字符
        //String reg = "^([A-Z]|[a-z]|[0-9]|[`-=[];,./~!@#$%^*()_+}{:?]){6,20}$";
        String regStr = "^([A-Z]|[a-z]|[0-9]|[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]){8,20}$";
        return password.matches(regStr);
    }


    /*public static void main(String[] args) {


    }*/






    /**
     * sha加密
     * @param message
     * @return
     */
    public static  String sha(String message) {
        try{
            MessageDigest md= MessageDigest.getInstance("SHA");
            md.update(message.getBytes());
            //System.out.println(md.digest());
            String s=new BigInteger(md.digest()).toString(32);
            System.out.println(s);
            return s;
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * md5加密 默认16
     * @param message m
     * @return s
     */
    public static  String md5(String message){
        return md5(message,16);
    }

    /**
     *
     * @param message 消息
     * @param radix 进制
     * @return 加密数据
     */
    public static String md5(String message,int radix){
        try{
            MessageDigest md= MessageDigest.getInstance("MD5");
            md.update(message.getBytes());
            //System.out.println(md.digest());
            String s=new BigInteger(md.digest()).toString(radix);
            // System.out.println(s);
            return s;
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return "";
    }

    static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 生成MD5码
     * @param plainText 要加密的字符串
     * @return md5值
     */
    public final static String MD5(String plainText) {
        try {
            byte[] strTemp = plainText.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成MD5码
     * @param plainText 要加密的字符串
     * @return md5值
     */
    public final static String MD5(byte[] plainText) {
        try {
            byte[] strTemp = plainText;
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 先进行HmacSHA1转码再进行Base64编码
     * @param data  要SHA1的串
     * @param key   秘钥
     * @return
     * @throws Exception
     */
    public static String HmacSHA1ToBase64(String data, String key) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }

    /**
     * 校验MD5码
     * @param text 要校验的字符串
     * @param md5 md5值
     * @return 校验结果
     */
    public static boolean valid(String text, String md5) {
        return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase());
    }

    /**
     * @param params
     * @return
     */
    public static String MD5(String... params) {
        StringBuilder sb = new StringBuilder();
        for (String param : params) {
            sb.append(param);
        }
        return MD5(sb.toString());
    }
}
